<?php

class Admini_ReturnGoodsController extends Uuch_ManageController {

    public function init() {
        parent::init();
        $this->appendCss('/admins/css/yundan.css');
        $this->appendCss('/admins/css/common.css');
        $this->appendScript('/admins/js/jquery/jquery-1.7.2.min.js')->appendScript('/js/jquery.validate.min.js')->appendScript('/js/messages_cn.js')->appendScript('/js/uuch.js');
        $this->appendScript('/js/jquery.json-2.4.min.js');
        $this->view->type = "returngoods";
        $this->view->recount0 = Application_Model_ReturnGoods::getCountByStatus(Application_Model_ReturnGoods::STATUS_Forpayment);
        $this->view->recount1 = Application_Model_ReturnGoods::getCountByStatus(Application_Model_ReturnGoods::STATUS_Payment);
        $this->view->recount2 = Application_Model_ReturnGoods::getCountByStatus(Application_Model_ReturnGoods::STATUS_Accepted);
        $this->view->recount3 = Application_Model_ReturnGoods::getCountByStatus(Application_Model_ReturnGoods::STATUS_Process);
        $this->view->recount4 = Application_Model_ReturnGoods::getCountByStatus(Application_Model_ReturnGoods::STATUS_Send);
        $this->view->recount5 = Application_Model_ReturnGoods::getCountByStatus(Application_Model_ReturnGoods::STATUS_Informed);
        $this->view->recount6 = Application_Model_ReturnGoods::getCountByStatus(Application_Model_ReturnGoods::STATUS_Received, 1);
        $this->view->recount9 = Application_Model_ReturnGoods::getCountByStatus(Application_Model_ReturnGoods::STATUS_Refund);
        $this->view->recount19 = Application_Model_ReturnGoods::getCountByStatus(Application_Model_ReturnGoods::STATUS_Received, 2);
        $this->view->recount10 = Application_Model_ReturnGoods::getCountByStatus(Application_Model_ReturnGoods::STATUS_Resend);
        $this->view->recount17 = Application_Model_ReturnGoods::getCountByStatus(null, null, Application_Model_ReturnGoods::Problem_Exception);
        $this->view->recount18 = Application_Model_ReturnGoods::getCountByStatus(null, null, Application_Model_ReturnGoods::Problem_Loss);
        $this->view->recount30 = Application_Model_ReturnGoods::getBeyondCount();
        $this->setTitle("退换货管理");
    }

    public function indexAction() {
        $quick = $this->getSafeParam("quick");
        $status = $this->getSafeParam("status");
        $pagesize = $this->getSafeParam("pagesize");
        $beyond = $this->getSafeParam("beyond");
        $typel = $this->getSafeParam("type");
        $all = $this->getSafeParam("all");
        if (!$pagesize) {
            $pagesize = 10;
        }
        $delete = $this->getSafeParam("delete");
        $start = $this->getSafeParam("start") ? $this->getSafeParam("start") : 0;
        $timescope = $this->getSafeParam('timescope');
        $starttime = $this->getSafeParam('starttime');
        $endtime = $this->getSafeParam('endtime');
        $problem = $this->getSafeParam("problem");

        if ($all == "all") {
            $starttime = "2013-01-01";
            $endtime = date('Y-m-d');
        }
        $strart = date("m") % 3 == 0 ? date("m") / 3 : ((int) (date("m") / 3) + 1);
        if ($timescope != null) {
            switch ($timescope) {
                case "yesterday":
                    $starttime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 1, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 1, date("Y")));
                    break;
                case "day3":
                    $starttime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 3, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d"), date("Y")));
                    break;
                case 'lastweek':
                    $starttime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - date("w") + 1 - 7, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - date("w") + 7 - 7, date("Y")));
                    break;
                case "week":
                    $starttime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - date("w") + 1, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - date("w") + 7, date("Y")));
                    break;
                case "month":
                    $starttime = date("Y-m-d", mktime(0, 0, 0, date("m"), 1, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("t"), date("Y")));
                    break;
                case "lastmonth":
                    $starttime = date("Y-m-d", mktime(0, 0, 0, date("m") - 1, 1, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, date("m") - 1, cal_days_in_month(CAL_GREGORIAN, date("m") - 1, date("Y")), date("Y")));
                    break;
                case "quarter":
                    $starttime = date("Y-m-d", mktime(0, 0, 0, ($strart - 1) * 3 + 1, 1, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, $strart * 3, cal_days_in_month(CAL_GREGORIAN, $strart * 3, date("Y")), date("Y")));
                    break;
                case "lastquarter":
                    $starttime = date("Y-m-d", mktime(0, 0, 0, ($strart - 1) * 3 - 2, 1, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, ($strart - 1) * 3, cal_days_in_month(CAL_GREGORIAN, ($strart - 1) * 3, date("Y")), date("Y")));
                    break;
                case "year":
                    $starttime = date("Y-m-d", mktime(0, 0, 0, 1, 1, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, 12, cal_days_in_month(CAL_GREGORIAN, 12, date("Y")), date("Y")));
                    break;
                case "lastyear":
                    $starttime = date("Y-m-d", mktime(0, 0, 0, 1, 1, date("Y") - 1));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, 12, cal_days_in_month(CAL_GREGORIAN, 12, date("Y") - 1), date("Y") - 1));
                    break;
                case "day7":
                    $starttime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 6, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d"), date("Y")));
                    break;
                case "day30":
                    $starttime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 30, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d"), date("Y")));
                    break;
                default :
                    $starttime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 90, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d"), date("Y")));
                    break;
            }
        } else {
            if ($starttime == null && $endtime == "") {
                $starttime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d"), date("Y") - 1));
                $endtime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d"), date("Y")));
            }
        }
        if ($status != null) {
            $this->view->stype = $status;
            if ($typel == 1 && $status == Application_Model_ReturnGoods::STATUS_Received) {
                $this->view->stype = 6;
            } else if ($typel == 2 && $status == Application_Model_ReturnGoods::STATUS_Received) {
                $this->view->stype = 19;
            }
        } else {
            $this->view->stype = 20;
        }
        if ($delete == 1) {
            $starttime = "";
            $endtime = "";
            $this->view->stype = 8;
            $isDelete = 1;
        } else {
            $isDelete = 0;
        }
        if ($beyond == 1) {
            $starttime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d"), date("Y") - 10));
            $endtime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 4, date("Y")));
            $this->view->stype = 30;
        }
        if ($problem == Application_Model_ReturnGoods::Problem_Exception) {
            $this->view->stype = 17;
        } else if ($problem == Application_Model_ReturnGoods::Problem_Loss) {
            $this->view->stype = 18;
        }
        $returnGoodsSearch = new Application_Model_Filter_ReturnGoodsSearch();
        $returnGoodsSearch->quick = $quick;
        $returnGoodsSearch->status = $status;
        $returnGoodsSearch->type = $typel;
        $returnGoodsSearch->starttime = $starttime;
        $returnGoodsSearch->endtime = $endtime;
        $returnGoodsSearch->isDelete = $isDelete;
        $returnGoodsSearch->beyond = $beyond;
        $returnGoodsSearch->problem = $problem;
        $this->view->res = Application_Model_ReturnGoods::getFilter($returnGoodsSearch, $pagesize, $start);
        $this->view->pagesize = $pagesize;
        $this->view->start = $start;
        $this->view->typel = $typel;
        $this->view->quick = $quick;
        $this->view->timescope = $timescope;
        $this->view->starttime = $starttime;
        $this->view->endtime = $endtime;
        $this->view->isDelete = $isDelete;
        $this->view->delete = $delete;
        $this->view->beyond = $beyond;
        $this->view->status = $status;
        $this->view->list = $this->view->res['list'];
        $this->view->type = "returngoods";
    }

    /**
     * 管理员申请退换货界面
     */
    public function exchangeAction() {
//        $storeid = $this->getSafeParam("storeid");
//        $storedetail = Application_Model_StoreItem::load($storeid);
//        $this->view->typel = $this->getSafeParam("type");
//        $this->view->storedetail = $storedetail;
        $idlist = $this->getSafeParam("idlist");
        $result = Application_Model_StoreItem::getstoreuser($idlist);
        if ($result == 2 || $result == 4) {
            $this->view->ma = $result;
        } else {
            $this->view->store = $result["storeItem"];
            $this->view->userInfo = Application_Model_User::load($result["userId"]);
        }
        $this->view->idlist = $idlist;
        $this->view->retuType = $this->getSafeParam("type");
        $this->view->type = "returngoods";
    }

    /**
     * 管理员申请退换货
     */
    public function applyAction() {
        $idlist = $this->getSafeParam("idlist");
        $returnAddress = $this->getSafeParam("returnAddress");
        $returnReason = $this->getSafeParam("returnReason");
        $type = $this->getSafeParam("type");
        $result = Application_Model_StoreItem::getstoreuser($idlist);
        if ($result == 2 || $result == 4) {
            $this->json(array("type" => $result));
        } else {
            $barcode = "";
            $isOrder = 0;
            foreach ($result["storeItem"] as $storeVal) {
                if ($type == Application_Model_ReturnGoods::TYPE_Return) {
                    $storeVal->Interior = Application_Model_StoreItem::Interior_ApplyForAlteration;
                    $storeVal->State = Application_Model_StoreItem::STATUS_ReturnOf;
                    if ($storeVal->Intype == "代购订单") {
                        $isOrder = 1;
                    }
                } else if ($type == Application_Model_ReturnGoods::TYPE_Change) {
                    $storeVal->Interior = Application_Model_StoreItem::Interior_Exchange;
                    $storeVal->State = Application_Model_StoreItem::STATUS_Exchange;
                }
                $storeVal->save();
                $barcode .= $storeVal->Barcode . ",";
            }
            $item = new Application_Model_ReturnGoods();
            $item->StoreItemId = $idlist;
            $item->UserId = $result["userId"];
            $item->ProductName = $barcode;
            $item->ReturnAddress = $returnAddress;
            $item->Type = $type;
            $item->ReturnReason = $returnReason;
            $item->Status = Application_Model_ReturnGoods::STATUS_Accepted;
            $item->Datetime = date("Y-m-d H:i:s");
            $item->Dotime = date("Y-m-d H:i:s");
            $item->CkPass = 0;
            if ($isOrder == 1) {
                $item->source = Application_Model_ReturnGoods::SOURCE_Agency;
            }
            $item->save();
            $item->addBillLog(Application_Model_ReturnGoods::STATUS_Accepted);
            Application_Model_Operate::addOperate(0, null, $barcode, "包裹申请退换货", $item->UserId);
            $this->json(array("type" => 1, "reid" => $item->Id));
        }
    }

    /**
     * 退换货详情
     */
    public function detailsAction() {
        $id = $this->getSafeParam("id");
        $detail = Application_Model_ReturnGoods::load($id);
        $words = array();
        for ($i = 0; $i < 26; $i++) {
            $words[] = chr(65 + $i);
        }
        $this->view->words = $words;
        $this->view->returnTypeAll = Application_Model_ReturnGoods::getReturnTypeAll();
        $this->view->detail = $detail;
        $this->view->stype = 20;
    }

    /**
     * 退换货----受理
     */
    public function acceptedAction() {
        $id = $this->getSafeParam("id");
        $opt = Application_Model_ReturnGoods::load($id);
        if ($opt && $opt->Status == Application_Model_ReturnGoods::STATUS_Payment) {
            $opt->Status = Application_Model_ReturnGoods::STATUS_Accepted;
            $opt->save();
            $opt->addBillLog(Application_Model_ReturnGoods::STATUS_Accepted);
            Application_Model_Operate::addOperate(0, null, $opt->productName, "退换货受理", $opt->UserId);
            $this->json(1);
        } else {
            $this->json(0);
        }
    }

    /**
     * 退换货----处理
     */
    public function dealAction() {
        $id = $this->getSafeParam("id");
        $opt = Application_Model_ReturnGoods::load($id);
        if ($opt && $opt->Status == Application_Model_ReturnGoods::STATUS_Accepted) {
            $opt->Status = Application_Model_ReturnGoods::STATUS_Process;
            $opt->save();
            $opt->addBillLog(Application_Model_ReturnGoods::STATUS_Process);
            Application_Model_Operate::addOperate(0, null, $opt->productName, "处理退换货", $opt->UserId);
            $this->json(1);
        } else {
            $this->json(0);
        }
    }

    /**
     * 退换货---发包
     */
    public function sendAction() {
        $id = $this->getSafeParam("id");
        $logisticsName = $this->getSafeParam("logisticsName");
        $logistics = $this->getSafeParam("logistics");
        $freight = $this->getSafeParam("freight") ? $this->getSafeParam("freight") : 0;
        $returnType = $this->getSafeParam("returnType");
        $opt = Application_Model_ReturnGoods::load($id);
        $userItem = Application_Model_UserAccount::load($opt->UserId);
        if (!$opt || $logisticsName == "" || $logistics == "" || $opt == "") {
            $this->json(0);
            return;
        }
        if ($returnType == Application_Model_ReturnGoods::Return_User) {
            if ($userItem->Money < $freight && 0 != $freight) {
                $opt->sendMessage($opt->ProductName, $opt->UserId, 1, $freight);
                $this->json(2);
                return;
            }
        }
        $opt->Status = Application_Model_ReturnGoods::STATUS_Send;
        $opt->LogisticsName = $logisticsName;
        $opt->Dotime = date("Y-m-d H:i:s");
        $opt->Logistics = $logistics;
        $opt->Freight = $freight;
        $opt->returnType = $returnType;
        $opt->save();
        $opt->addBillLog(Application_Model_ReturnGoods::STATUS_Send);
        Application_Model_Operate::addOperate(0, null, $opt->productName, "退换货发包", $opt->UserId);
        //扣除用户的运费
        if ($opt->Freight > 0) {
            if ($returnType == Application_Model_ReturnGoods::Return_User) {
                $opt->deductFreight($opt->productName, $opt->UserId, $opt->Freight, "包裹(" . $opt->ProductName . ")退货产生运费");
                $afterMoney = $userItem->Money;
                $beforeMoney = $afterMoney - $freight;
                $params = array('businessType' => 'fhyf','order_sn'=>$opt->id, 'beforeMoney' => $beforeMoney, 'afterMoney' => $afterMoney, 'account' => $userItem, 'trader' => 'account-number-cr');
                if ($opt->type == Application_Model_ReturnGoods::TYPE_Change) {
                    $params['businessType'] = 'hhfahuoyunfei';
                }
                $params['attribute'] = json_encode(array('express_company' => $logisticsName));
                $this->_addFinance($freight, $params);
                $params['trader'] = 'backend-account-dr';
                $params['beforeMoney'] = $params['afterMoney'];
                $this->_addFinance($freight, $params);
                $params['trader'] = 'backend-account-cr';
                $this->_addFinance($freight, $params);
                $params['trader'] = 'yq-uuchcn-dr';
                $this->_addFinance($freight, $params);
                $params['trader'] = 'yq-uuchcn-cr';
                $this->_addFinance($freight, $params);
                $params['trader'] = 'ec-account-dr';
                $this->_addFinance($freight, $params);
            } else {
                $applyName = Uuch_Util::getUserNikeName();
                $needAddMoney = ($opt->returnType == Application_Model_ReturnGoods::Return_Seller) ? Application_Model_FinancialCheckItem::Money_ReturnSeller : Application_Model_FinancialCheckItem::Money_ReturnUuch;
                Application_Model_FinancialCheckItem::addCheckItem(Application_Model_DomainobjectType::ObjectType_ReturnGoods, $opt->Id, $opt->Freight, $opt->TypeName . "的运费由" . $opt->ReturnTypeName, $applyName, $opt->UserId, $needAddMoney);
                if ($opt->returnType == Application_Model_ReturnGoods::Return_Uuch) {
                    $afterMoney = $userItem->Money;
                    $beforeMoney = $afterMoney;
                    $params = array('businessType' => 'fhyf','order_sn'=>$opt->id, 'beforeMoney' => $beforeMoney, 'afterMoney' => $afterMoney, 'account' => $userItem);
                    if ($opt->type == Application_Model_ReturnGoods::TYPE_Change) {
                        $params['businessType'] = 'hhfahuoyunfei';
                    }
                    $params['attribute'] = json_encode(array('express_company' => $logisticsName));
                    $params['trader'] = 'yq-uuchcn-cr';
                    $this->_addFinance($freight, $params);
                    $params['trader'] = 'ec-account-dr';
                    $this->_addFinance($freight, $params);
                }
            }
        }

        $this->json(1);
    }

    /**
     * 退换货---通知客户
     */
    public function noticeAction() {
        $id = $this->getSafeParam("id");
        $opt = Application_Model_ReturnGoods::load($id);
        if ($opt && $opt->Status == Application_Model_ReturnGoods::STATUS_Send) {
            $opt->Status = Application_Model_ReturnGoods::STATUS_Informed;
            $opt->save();
            /**
             * 发站内信通知用户
             */
            $mailItem = new Application_Model_Mail();
            $mailItem->title = "尊敬的客户，您好！您的退换货有了新的进展";
            $mailItem->userId = $opt->UserId;
            $mailItem->type = 1;
            $mailItem->message = "您需要" . $opt->TypeName . "的商品（" . $opt->ProductName . "）已出悠奇仓库（" . $opt->logisticsName . "：" . $opt->logistics . "），我们已通知了卖家注意收货，注：自助包裹还请自行与卖家联系。";
            $mailItem->status = 0;
            $mailItem->dateCreated = date('Y-m-d H:i:s');
            $mailItem->save();
            $opt->addBillLog(Application_Model_ReturnGoods::STATUS_Informed);
            Application_Model_Operate::addOperate(0, null, $opt->productName, "退换货通知用户已发包", $opt->UserId);
            $this->json(1);
        } else {
            $this->json(0);
        }
    }

    /**
     * 退换货---对方收件
     */
    public function waitingreceiptAction() {
        $id = $this->getSafeParam("id");
        $opt = Application_Model_ReturnGoods::load($id);
        if ($opt && $opt->Status == Application_Model_ReturnGoods::STATUS_Informed) {
            $opt->Status = Application_Model_ReturnGoods::STATUS_Received;
            $opt->save();
            $opt->addBillLog(Application_Model_ReturnGoods::STATUS_Received);
            Application_Model_Operate::addOperate(0, null, $opt->productName, "退换货对方已收件", $opt->UserId);
            //代购包裹  给用户发站内信
            if ($opt->Source == Application_Model_ReturnGoods::SOURCE_Agency) {
                $opt->sendMessage($opt->ProductName, $opt->UserId);
            }
            $this->json(1);
        } else {
            $this->json(0);
        }
    }

    /**
     * 退换货---卖家退款
     */
    public function refundAction() {
        $id = $this->getSafeParam("id");
        $opt = Application_Model_ReturnGoods::load($id);
        if ($opt && $opt->Status == Application_Model_ReturnGoods::STATUS_Received) {
            $opt->Status = Application_Model_ReturnGoods::STATUS_Refund;
            $opt->save();
            $opt->addBillLog(Application_Model_ReturnGoods::STATUS_Refund);
            Application_Model_Operate::addOperate(0, null, $opt->productName, "退货卖家已退款", $opt->UserId);
            $this->json(1);
        } else {
            $this->json(0);
        }
    }

    /**
     * 退换货---完成
     */
    public function succeedAction() {
        $id = $this->getSafeParam("id");
        $opt = Application_Model_ReturnGoods::load($id);
        if ($opt && ($opt->Status == Application_Model_ReturnGoods::STATUS_Received || $opt->Status == Application_Model_ReturnGoods::STATUS_Refee || $opt->Status == Application_Model_ReturnGoods::STATUS_Receipt)) {
            $opt->Status = Application_Model_ReturnGoods::STATUS_Succeed;
            $opt->save();
            $isOrder = 0;
            $storeItem = $opt->StoreInfo;
            foreach ($storeItem as $storeVal) {
                if ($opt->Type == Application_Model_ReturnGoods::TYPE_Return) {
                    $storeVal->Interior = Application_Model_StoreItem::Interior_AchieveReturn;
                    $storeVal->State = Application_Model_StoreItem::STATUS_AchieveRe;
                    $storeVal->Isdelete = 1;
                    if ($storeVal->Intype == "代购订单") {
                        $isOrder = 1;
                    }
                } else {
                    $storeVal->Interior = Application_Model_StoreItem::Interior_AchieveExchange;
                    $storeVal->State = Application_Model_StoreItem::STATUS_AchieveExchange;
                    $storeVal->Isdelete = 1;
                }
                $storeVal->save();
            }
            $opt->addBillLog(Application_Model_ReturnGoods::STATUS_Succeed);
            Application_Model_Operate::addOperate(0, null, $opt->productName, "退换货完成", $opt->UserId);
            $this->json(array("type" => 1, "isOrder" => $isOrder));
        } else {
            $this->json(array("type" => 0));
        }
    }

    /**
     * 退换货---对方已发件
     */
    public function resendAction() {
        $id = $this->getSafeParam("id");
        $reLogisticsName = $this->getSafeParam("reLogisticsName");
        $reLogistics = $this->getSafeParam("reLogistics");
        $reFreight = $this->getSafeParam("reFreight");
        $opt = Application_Model_ReturnGoods::load($id);
        $userItem = Application_Model_UserAccount::load($opt->UserId);
        if ($opt && $opt->Status == Application_Model_ReturnGoods::STATUS_Received) {
            if ($userItem->Money >= $reFreight) {
                $opt->Status = Application_Model_ReturnGoods::STATUS_Resend;
                $opt->ReLogisticsName = $reLogisticsName;
                $opt->ReLogistics = $reLogistics;
                $opt->ReFreight = $reFreight;
                $opt->ReDatetime = date("Y-m-d H:i:s");
                $opt->save();
                $opt->addBillLog(Application_Model_ReturnGoods::STATUS_Resend);
                Application_Model_Operate::addOperate(0, null, $opt->productName, "换货对方已发出", $opt->UserId);

                //扣除用户的运费
//                $opt->deductFreight($opt->ProductName,$opt->UserId, $opt->ReFreight, "包裹(".$opt->ProductName.")换货产生运费");
                if ($opt->returnType == Application_Model_ReturnGoods::Return_User) {
                    $opt->deductFreight($opt->productName, $opt->UserId, $opt->ReFreight, "包裹(" . $opt->ProductName . ")退货产生运费");
                    $afterMoney = $userItem->Money;
                    $beforeMoney = $afterMoney - $reFreight;
                    $params = array('businessType' => 'shouhuoyunfei','order_sn'=>$opt->id, 'beforeMoney' => $beforeMoney, 'afterMoney' => $afterMoney, 'account' => $userItem, 'trader' => 'account-number-cr');
                    $params['attribute'] = json_encode(array('express_company' => $reLogisticsName));
                    $this->_addFinance($reFreight, $params);
                    $params['trader'] = 'backend-account-dr';
                    $params['beforeMoney'] = $params['afterMoney'];
                    $this->_addFinance($reFreight, $params);
                    $params['trader'] = 'backend-account-cr';
                    $this->_addFinance($reFreight, $params);
                    $params['trader'] = 'yq-uuchcn-dr';
                    $this->_addFinance($reFreight, $params);
                    $params['trader'] = 'yq-uuchcn-cr';
                    $this->_addFinance($reFreight, $params);
                    $params['trader'] = 'ec-account-dr';
                    $this->_addFinance($reFreight, $params);
                } else {
                    $applyName = Uuch_Util::getUserNikeName();
                    $needAddMoney = ($opt->returnType == Application_Model_ReturnGoods::Return_Seller) ? Application_Model_FinancialCheckItem::Money_ReturnSeller : Application_Model_FinancialCheckItem::Money_ReturnUuch;
                    Application_Model_FinancialCheckItem::addCheckItem(Application_Model_DomainobjectType::ObjectType_ReturnGoods, $opt->Id, $opt->Freight, $opt->TypeName . "的运费由" . $opt->ReturnTypeName, $applyName, $opt->UserId, $needAddMoney);
                    if ($opt->returnType == Application_Model_ReturnGoods::Return_Uuch) {
                        $params = array('businessType' => 'shouhuoyunfei','order_sn'=>$opt->id, 'beforeMoney' => $beforeMoney, 'afterMoney' => $afterMoney, 'account' => $userItem);
                        $params['attribute'] = json_encode(array('express_company' => $reLogisticsName));
                        $params['trader'] = 'yq-uuchcn-cr';
                        $this->_addFinance($reFreight, $params);
                        $params['trader'] = 'ec-account-dr';
                        $this->_addFinance($reFreight, $params);
                    }
                }
                $this->json(1);
            } else {
                $opt->sendMessage($opt->ProductName, $opt->UserId, 2, $reFreight);
                $this->json(2);
            }
        } else {
            $this->json(0);
        }
    }

    /**
     * 退换货---仓库已收件
     */
    public function receiptAction() {
        $id = $this->getSafeParam("id");
        $opt = Application_Model_ReturnGoods::load($id);
        if ($opt && $opt->Status == Application_Model_ReturnGoods::STATUS_Resend) {
            $opt->Status = Application_Model_ReturnGoods::STATUS_Receipt;
            $opt->save();
            $opt->addBillLog(Application_Model_ReturnGoods::STATUS_Receipt);
            Application_Model_Operate::addOperate(0, null, $opt->productName, "换货仓库已收件", $opt->UserId);
            $this->json(1);
        } else {
            $this->json(0);
        }
    }

    /**
     * 根据id修改后台状态
     */
    public function changeinteriorAction() {
        $id = $this->getSafeParam("id");
        $interior = $this->getSafeParam("interior");
        $opt = Application_Model_ReturnGoods::load($id);
        if ($opt) {
            $opt->Status = $interior;
            $opt->save();
            Application_Model_Operate::addOperate(0, null, $opt->productName, "修改退换货状态为：".$opt->StatusName, $opt->UserId);
            $opt->delLog();
            $this->json(1);
        } else {
            $this->json(0);
        }
    }

    /**
     * 根据id，标记删除
     */
    public function deletebyidAction() {
        $id = $this->getSafeParam("id");
        $opt = Application_Model_ReturnGoods::load($id);
        if ($opt && $opt->status >= Application_Model_ReturnGoods::STATUS_Send && $opt->IsDelete != 1) {
            $this->json(2);
        } else {
            $opt->IsDelete = 1;
            $opt->save();
            $storeItem = $opt->StoreInfo;
            $barcode = "";
            foreach ($storeItem as $storeVal) {
                $storeVal->Interior = Application_Model_StoreItem::Interior_InStored;
                $storeVal->State = Application_Model_StoreItem::STATUS_InStored;
                $storeVal->Isdelete = 0;
                $storeVal->save();
                $barcode .= $storeVal->Barcode . ",";
            }
            Application_Model_Operate::addOperate(0, null, $opt->productName, "状态为：".$opt->StatusName."退换货标记删除", $opt->UserId);
            $this->json(1);
        }
    }

    /**
     * 修改备注
     */
    public function editremarkAction() {
        $id = $this->getSafeParam("id");
        $remark = $this->getSafeParam("remark");
        $opt = Application_Model_ReturnGoods::load($id);
        if ($opt) {
            $opt->ReturnNote = $remark;
            $opt->save();
            Application_Model_Operate::addOperate(0, null, $opt->productName, "退换货添加备注", $opt->UserId);
            $this->json(1);
        } else {
            $this->json(0);
        }
    }

    /**
     * 标注异常 并 记录异常信息
     */
    public function abnormalAction() {
        $id = $this->getSafeParam("id");
        $exception = $this->getSafeParam("exception");
        $opt = Application_Model_ReturnGoods::load($id);
        if ($opt) {
            $opt->Exception = $exception;
            $opt->Problem = Application_Model_ReturnGoods::Problem_Exception;
            Application_Model_Operate::addOperate(0, null, $opt->productName, "退换货标记异常", $opt->UserId);
            $opt->save();
            $this->json(1);
        } else {
            $this->json(0);
        }
    }

    public function processAction() {
        $id = $this->getSafeParam("id");
        $exception = $this->getSafeParam("exception");
        $opt = Application_Model_ReturnGoods::load($id);
        if ($opt) {
            $opt->Exception = $exception;
            $opt->Problem = Application_Model_ReturnGoods::Problem_Process;
            Application_Model_Operate::addOperate(0, null, $opt->productName, "异常退换货标记已处理", $opt->UserId);
            $opt->save();
            $this->json(1);
        } else {
            $this->json(0);
        }
    }

    /**
     * 标注包裹丢失 并 记录信息
     */
    public function lossAction() {
        $id = $this->getSafeParam("id");
        $exception = $this->getSafeParam("exception");
        $opt = Application_Model_ReturnGoods::load($id);
        if ($opt) {
            $opt->Exception = $exception;
            $opt->Problem = Application_Model_ReturnGoods::Problem_Loss;
            Application_Model_Operate::addOperate(0, null, $opt->productName, "退换货标记包裹丢失", $opt->UserId);
            $opt->save();
            $this->json(1);
        } else {
            $this->json(0);
        }
    }

    /**
     * 代购退货  -- 退款给客户
     */
    public function rechargeAction() {
        $id = $this->getSafeParam("id");
        $opt = Application_Model_ReturnGoods::load($id);
        $orecharge = $this->getSafeParam('orecharge');

        if ($opt && $opt->Type == Application_Model_ReturnGoods::TYPE_Return && $opt->Source == Application_Model_ReturnGoods::SOURCE_Agency && $opt->Status == Application_Model_ReturnGoods::STATUS_Refund) {
            $opt->Status = Application_Model_ReturnGoods::STATUS_Refee;
            $opt->save();
            $opt->addBillLog(Application_Model_ReturnGoods::STATUS_Refee);
            $recharge = $this->getSafeParam("recharge");
            $rechargeRemark = $this->getSafeParam("rechargeRemark");
            $res = Application_Model_User::editmoney($opt->UserId, $recharge, $rechargeRemark, "message", "recharge");
            $applyName = Uuch_Util::getUserNikeName();
            Application_Model_FinancialCheckItem::addCheckItem(Application_Model_DomainobjectType::ObjectType_ReturnGoods, $opt->Id, $recharge, $rechargeRemark, $applyName, $opt->UserId, Application_Model_FinancialCheckItem::Money_orderReturn);
            Application_Model_Operate::addOperate($recharge, null, $opt->productName, "代购包裹退货提款给用户", $opt->UserId);
            if ($res == 3) {
                $this->json(1);       //成功！
                $userItem = Application_Model_UserAccount::load($opt->UserId);
                $afterMoney = $userItem->Money;
                $beforeMoney = $afterMoney - $recharge;
                $params = array('businessType' => 'thspjz','order_sn'=>$opt->id, 'beforeMoney' => $beforeMoney, 'afterMoney' => $beforeMoney, 'account' => $userItem, 'trader' => 'seller-number-cr');
                $params['remark'] = $rechargeRemark;
                $this->_addFinance($recharge, $params);
                $params['trader'] = 'yq-uuchcn-dr';
                $this->_addFinance($recharge, $params);
                $params['trader'] = 'yq-uuchcn-cr';
                $this->_addFinance($recharge, $params);
                $params['trader'] = 'backend-account-dr';
                $this->_addFinance($recharge, $params);
                $params['trader'] = 'backend-account-cr';
                $this->_addFinance($recharge, $params);
                $params['trader'] = 'account-number-dr';
                $params['afterMoney'] = $afterMoney;
                $this->_addFinance($recharge, $params);
                if($orecharge){
                    $this->_addOrderReturnFinance($orecharge, $params);
                }
            } else {
                $this->json(0);      //操作失败！
            }
        } else {
            $this->json(0);         //操作失败！
        }
    }
    
    protected function _addOrderReturnFinance($orecharge,$data){
        $orecharge = htmlspecialchars_decode($orecharge);
        $orderRecharge = json_decode($orecharge);
        $data['businessType'] = 'dg-spjz';
        $data['beforeMoney'] = $data['afterMoney'];
        foreach ($orderRecharge as $_recharge){
            $data['trader'] = 'backend-account-cr';
            $data['order_sn'] = $_recharge->order_sn;
            $this->_addFinance($_recharge->value, $data);
            $data['trader'] = 'account-number-dr';
            $this->_addFinance($_recharge->value, $data);
        }
        return $this;
    }

    protected function _addFinance($money, $params) {

        $account = $params['account'];
        require_once(APPLICATION_PATH . '/../library/finance/General.php');
        $user = Application_Model_User::load($account->id);
        $remark = isset($params['remark']) ? $params['remark'] : '';
        $orderSn = isset($params['order_sn']) ? $params['order_sn'] : '';
        $data = array(
            'transaction_number' => '',
            'trader' => $params['trader'],
            'customer_id' => $account->id,
            'customer_name' => $user->nikename,
            'member' => 'admin',
            'amount' => $money,
            'currency' => 'CNY',
            'rate' => '1',
            'rate_amount' => '0',
            'period_start' => $params['beforeMoney'],
            'period_end' => $params['afterMoney'],
            'business_type' => $params['businessType'],
            'order_sn' => $orderSn,
            'remark' => $remark,
            'created_at' => date('Y-m-d H:i:s')
        );
        if (isset($params['attribute'])) {
            $data['attribute'] = $params['attribute'];
        }
        try {
            $api = new General($params['beforeMoney'], $account);
            $api->setFields($data);
            $api->addTransaction();
            $result = array('code' => 'success', 'message' => '');
        } catch (Exception $ex) {
            echo $ex->getMessage();
            $result = array('code' => 'error', 'message' => $ex->getMessage());
        }
    }

}
